package servlet;

import model.DBUtil;
import model.Puser;
import model.Ruser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.sql.*;

@WebServlet("/new-register")
public class NewRegister extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Integer role = Integer.valueOf(req.getParameter("role"));
        String username = req.getParameter("username");
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex");
        PrintWriter out = resp.getWriter();
        if (role==1){
            if (username.length() == 0 || phone.length() == 0 || password.length() == 0 || email.length() == 0) {
                out.print("<script language='javascript'>alert('Please fill in the registration information correctly!!!');window.location.href='/new-register.html';</script>");
                return;
            }
        Puser puser;
        try {
            puser = save1(username, phone, password, email,age,sex);

            HttpSession session = req.getSession();
            session.setAttribute("pcurrentUser", puser);

            //完成登录
            //引导浏览器回到首页
            resp.sendRedirect("/");
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }
        if (role==2){
            if(username.length()==0||phone.length()==0||password.length()==0||email.length()==0){
                out.print("<script language='javascript'>alert('Please fill in the registration information correctly!!');window.location.href='/new-register.html';</script>");
                return;
            }
            Ruser ruser;
            try {
                ruser = save2(username, phone, password,email);

                HttpSession session = req.getSession();
                session.setAttribute("rcurrentUser", ruser);

                //完成登录
                //引导浏览器回到首页
                resp.sendRedirect("/");
            } catch (SQLException throwable) {
                throwable.printStackTrace();
            }
        }
    }

    private Puser save1(String username, String phone, String password,String email,String age,String sex) throws SQLException {
        password = hash(password);
        try (Connection c = DBUtil.getConnection()) {
            String sql = "INSERT INTO puser(pusername,phone,ppassword,email,age,sex) VALUES(?,?,?,?,?,?)";
            try (PreparedStatement s = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                s.setString(1, username);
                s.setString(2, phone);
                s.setString(3,  password);
                s.setString(4,  email);
                s.setString(5,  age);
                s.setString(6,  sex);


                s.executeUpdate();

                try (ResultSet rs = s.getGeneratedKeys()) {
                    if (!rs.next()) {
                        return null;
                    }
                    Puser user = new Puser();
                    user.pusername = username;
                    user.phone = phone;
                    user.ppasswprd = password;
                    user.email = email;
                    user.age = age;
                    user.sex = sex;
                    user.puid = rs.getInt(1);
                    return user;
                }
            }
        }
    }
    private Ruser save2(String username, String phone, String password,String email) throws SQLException {
        password = hash(password);
        try (Connection c = DBUtil.getConnection()) {
            String sql = "INSERT INTO ruser(rname,rphone,rpassword,remail) VALUES(?,?,?,?)";
            try (PreparedStatement s = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                s.setString(1, username);
                s.setString(2, phone);
                s.setString(3,  password);
                s.setString(4,  email);

                s.executeUpdate();

                try (ResultSet rs = s.getGeneratedKeys()) {
                    if (!rs.next()) {
                        return null;
                    }
                    Ruser user = new Ruser();
                    user.rname = username;
                    user.rphone = phone;
                    user.rpassword = password;
                    user.remail = email;
                    user.ruid = rs.getInt(1);
                    return user;
                }
            }
        }
    }

    private String hash(String ppassword) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
            byte[] bytes = ppassword.getBytes("UTF-8");
            byte[] digest = messageDigest.digest(bytes);
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();

        }catch (Exception exc){
            return ppassword;
        }
    }
}
